﻿using BCService.WeChatComponent.WeChatAccessTokenService;
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WeChatSDK.Common;
using WeChatSDK.Common.Enums.MessageEncoding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using WeChatSDK.WeChatServiceComponent.Conversation.BaseSupport;

namespace BCTMSRESTful.Configs
{
    public static class WeChatExtension
    {
        public static IApplicationBuilder ConfigureWeChat(this IApplicationBuilder app, IConfiguration configuration)
        {
            WeChatInfo.AppId = configuration["WeChatService:AppId"];
            WeChatInfo.Secret = configuration["WeChatService:AppSecret"];
            WeChatInfo.Token = configuration["WeChatService:Token"];
            WeChatInfo.MiniProgramAppId = configuration["WeChatApplets:AppId"];
            WeChatInfo.MiniProgramAppSecret = configuration["WeChatApplets:AppSecret"];
            WeChatInfo.EncodingAESKey = configuration["WeChatService:EncodingAESKey"];
            WeChatInfo.EncodingType = (WeChatMessageEncodingType)int.Parse(configuration["WeChatService:EncodingType"]);

            WeChatGeneral.ChangeTokenEvent += (weChatAccessTokenDto) =>
            {
                IWeChatAccessTokenService weChatAccessTokenService = app.ApplicationServices.GetService<IWeChatAccessTokenService>();
                BaseSupportService.WeChatAccessTokenDto = weChatAccessTokenService.Update(weChatAccessTokenDto);
            };

            WeChatGeneral.TakeTokenEvent += () =>
            {
                IWeChatAccessTokenService weChatAccessTokenService = app.ApplicationServices.GetService<IWeChatAccessTokenService>();
                BaseSupportService.WeChatAccessTokenDto = weChatAccessTokenService.Get();
            };

            return app;
        }
    }
}
